package com.xb.loan.cashier.biz.task.alipay;

import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.pay.alipay.AlipayPayment;
import com.xb.loan.cashier.biz.service.CashierEncashOrderService;
import com.xb.loan.cashier.biz.service.CashierPayChannelService;
import com.xb.loan.cashier.biz.task.ThirdQueryEncashTask;
import com.xb.loan.cashier.biz.util.Configure;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component(value="alipayWapQueryEncashTask")
@Scope(value="prototype")
public class AlipayWapQueryEncashTask extends ThirdQueryEncashTask {
	
    private static final Logger logger = LoggerFactory.getLogger(AlipayWapQueryEncashTask.class);

    @Autowired
    private CashierPayChannelService cashierPayChannelService;
    @Autowired
    private CashierEncashOrderService cashierEncashOrderService;
    
	@Override
	public void execute() {
		//付款文件名称,必填，必须含有扩展名，如：20120711.csv
		String fileName = cashierEncashBatch.getFileName();
		String payChannelId = cashierEncashBatch.getPayChannelId();
	    try {
	        CashierPayChannel channel = cashierPayChannelService.selectByPayChannelId(payChannelId);
	        if(channel==null || channel.getPaychannelType()!= ICashierEnumConst.CashierPayChannelType.ALIPAY.getType()){
	            logger.warn("cashier 提现查询失败，渠道不存在 payChannelId="+payChannelId + ",批次=" + cashierEncashBatch.getBatchId());
	            return;
	        }
	        
	        // 加密类型需要根据平台区分，这里由于可能有多个渠道，默认用MD5
	        int signTypeValue = ICashierEnumConst.CashierEncryptType.MD5.getEncryptType();
	        String payUrl = channel.getPayUrl();
	        String partner = channel.getChannelUser();
	        String signType = null;
            String signKey = null;
	        if(signTypeValue== ICashierEnumConst.CashierEncryptType.MD5.getEncryptType()){
	            signKey = channel.getMd5Key();
	            signType = ICashierEnumConst.CashierEncryptType.MD5.getDesc();
	        }else if(signTypeValue== ICashierEnumConst.CashierEncryptType.RSA.getEncryptType()){
	            signKey = channel.getPrivateKey();
	            signType = ICashierEnumConst.CashierEncryptType.RSA.getDesc();
	        }
	        
	        // 下载结果文件
	        String resultFilePath = Configure.getStringValue("task.encashresult.alipay.file.path");
	        boolean isSuccess = AlipayPayment.bptb_result_file(fileName, resultFilePath, partner, signType, signKey, payUrl);
	        if(!isSuccess){
	            logger.warn("支付宝提现查询文件下载异常  批次="+cashierEncashBatch.getBatchId() + "，渠道为："+partner);
	            return;
	        }
	        
	        // 处理提现结果
	        cashierEncashOrderService.updateEncashResultFile(resultFilePath, fileName);
        } catch (Exception e) {
            logger.error("支付宝提现查询任务异常", e);
            if (e instanceof IOException) {
            	/* 需下载的批次已被废除，被废除的原因有如下三种：
	            1、用户在上传文件时选择需复核，但自上传之日起15天内 没有进行复核操作，批次自动被系统废除
	            2、付款账户余额不足，且在用户上传当天的23：30前仍未 向账户中充入足够的金额，批次自动被系统废除
	            3、支付宝后台废除*/
            	if ("文件下载失败！该批次已废除。".equals(e.getMessage())) {
            		try {
						cashierEncashOrderService.updateBatchOrder(cashierEncashBatch.getBatchId(),fileName,ICashierEnumConst.CashierEncashStatus.FAIL.getStatus(), new Date(), e.getMessage());
					} catch (Exception e1) {
						logger.error("execute",e);
					}
            	}
			}
        }
	    
	}
	
}
